package com.open.system.service.impl;

import com.open.common.utils.CollectionUtils;
import com.open.system.mapper.UserMapper;
import com.open.common.model.Page;
import com.open.common.model.Sort;
import com.open.base.model.User;
import com.open.system.service.IUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 用户信息
 *
 * @author 大树03
 * @date 2025-02-01 22:47
 */
@Service(value = "userService")
@Slf4j
public class UserServiceImpl implements IUserService {

    private UserMapper userMapper;

    @Autowired
    public void setUserMapper(UserMapper userMapper) {
        this.userMapper = userMapper;
    }

    @Override
    @Transactional()
    public Boolean save(User model) {
        return userMapper.save(model);
    }

    @Override
    @Transactional()
    public Boolean update(User model) {
        return userMapper.update(model);
    }

    @Override
    public Page<User> findPage(Page<User> page, User item) {
        Map<String, Object> map = new HashMap<String, Object>(4);
        int startPoint = (page.getIndex() - 1) * page.getSize();
        map.put("orderBy", new Sort());
        map.put("item", item);
        map.put("startPoint", startPoint);
        map.put("endPoint", page.getSize());
        Integer count = userMapper.findPageCount(map);
        if (count > startPoint) {
            page.setItems(userMapper.findPage(map));
        } else {
            page.setItems(new ArrayList<User>());
        }
        page.setTotal(count);
        return page;
    }

    @Override
    public List<User> findByModel(User item) {
        Map<String, Object> map = new HashMap<String, Object>(1);
        map.put("item", item);
        return userMapper.findByModel(map);
    }

    @Override
    public User findByPk(Long pk) {
        return userMapper.findByPk(pk);
    }

    @Override
    public Integer countByModel(User item) {
        Map<String, Object> map = new HashMap<String, Object>(1);
        map.put("item", item);
        return userMapper.findPageCount(map);
    }

    @Override
    @Transactional()
    public Boolean remove(List<Long> pks) {
        for (Long pk : pks) {
            userMapper.remove(pk);
        }
        return true;
    }

    @Override
    public List<String> findExistingUsernames(List<String> usernames) {
        if (usernames == null || usernames.isEmpty()) {
            return new ArrayList<>();
        }
        return userMapper.findExistingUsernames(usernames);
    }

    @Override
    public Boolean batchSave(List<User> lists) {
        if (CollectionUtils.isEmpty(lists)) {
            return false;
        }
        return userMapper.batchSave(lists);
    }
}